package cn.itcast.login;

import cn.itcast.base.BaseController;
import cn.itcast.domain.Module;
import cn.itcast.domain.User;
import cn.itcast.domain.feedback.Feedback;
import cn.itcast.service.feedback.FeedbackService;
import cn.itcast.service.module.ModuleService;
import cn.itcast.service.user.UserService;
import cn.itcast.shiro.WxOpenIdToken;

import cn.itcast.utils.AipFaceHelper;
import cn.itcast.utils.HttpUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
public class LoginController extends BaseController {

    private static String AppID = "wx3bdb1192c22883f3";
    private static String AppSecret = "db9d6b88821df403e5ff11742e799105";

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    @Autowired
    private FeedbackService feedbackService;
    /*@RequestMapping("/login")
    public String login(String email,String password) {

        //1 登录不成功（login.jsp）
        if(UtilFuns.isEmpty(email) || UtilFuns.isEmpty(password)){
            // 登录失败--账号密码为空
            return "forward:login.jsp";
        }

        //2 账号密码为空---去数据库查询
        User user=userService.findByUser(email);
        if(user==null || !user.getPassword().equals(password)){
            // 登录失败--账号密码不匹配
            request.setAttribute("error","账号或密码错误...");
            return "forward:login.jsp";
        }

        //3 登录成功
        session.setAttribute("loginUser",user);

        //4 控制：想办法在页面展示出当前登录用户应该具备的菜单吧
        List<Module> menus=moduleService.findMenus(user);
        session.setAttribute("modules",menus);
        return "home/main";
    }*/


    @RequestMapping(value = "/login", name = "shiro做登录认证")
    public String login(String email, String password) {

        try {

            //shiro认证
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken uptoken = new UsernamePasswordToken(email, password);
            subject.login(uptoken); //入口开始

            //登录认证成功的用户放入session
            User user = (User) subject.getPrincipal();
            session.setAttribute("loginUser", user);
            // 将该登录用户的菜单查询出来在页面动态构造菜单
            List<Module> menus = moduleService.findMenus(user);
            session.setAttribute("modules", menus);

        } catch (Exception e) {
            // 登录失败--账号密码不匹配
            request.setAttribute("error", "账号或密码错误...");
            return "forward:login.jsp";
        }
        showlist();
        return "home/main";
    }

    @RequestMapping(value = "/faceLogin")
    public String faceLogin(String images) {
        String id = AipFaceHelper.faceSearch(images);

        if (id!=null){
            User user = userService.findByIdd(id);
            if (user==null){
                request.setAttribute("error","刷脸登录失败");
            }else {
                //shiro认证
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken uptoken=new UsernamePasswordToken(user.getEmail(),user.getPasswd());
                subject.login(uptoken); //入口开始
                //登录认证成功的用户放入session
                User user1 =(User)subject.getPrincipal();
                session.setAttribute("loginUser",user1);
                // 将该登录用户的菜单查询出来在页面动态构造菜单
                List<Module> menus=moduleService.findMenus(user1);
                session.setAttribute("modules",menus);
            }

        }else{
            request.setAttribute("error","刷脸登录失败");
            return "forward:/login.jsp";
        }

        return "home/main";
    }
    //退出
    @RequestMapping(value = "/logout", name = "用户登出")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();//shiro的登录用户登出
        subject.logout();
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home() {

        return "home/home";
    }

    @RequestMapping("/weixinlogin")
    public String weixinlogin(String code) {
        System.out.println("我是好人啊-----------------------------");
        String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppID + "&secret=" + AppSecret + "&code=" + code + "&grant_type=authorization_code";
        Map<String, Object> stringObjectMap = HttpUtils.sendGet(token_url);

        String access_token = (String) stringObjectMap.get("access_token");
        String openid = (String) stringObjectMap.get("openid");
        String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
        Map<String, Object> userMap = HttpUtils.sendGet(user_url);
        String openId = (String) userMap.get("openid");

        User user = userService.findByOpenId(openId);
        if (user == null) {
            request.setAttribute("openId", openId);
            return "login/login-email";
        }

        Subject subject = SecurityUtils.getSubject();
        WxOpenIdToken wxOpenIdToken = new WxOpenIdToken(openId);
        subject.login(wxOpenIdToken);
        List<Module> menus = moduleService.findMenus(user);
        session.setAttribute("modules", menus);
        session.setAttribute("loginUser", user);
        return "home/main";
    }

    @RequestMapping("/LoginEmail")
    public String LoginEmail(String email, String openId) {

        User byUser = userService.findByUser(email);
        if (byUser == null) {
            request.setAttribute("error", "请输入本公司的员工email");
            return "login/login-email";
        } else {
            byUser.setOpenId(openId);
            userService.update(byUser);
        }


        Subject subject = SecurityUtils.getSubject();
        WxOpenIdToken wxOpenIdToken = new WxOpenIdToken(openId);
        subject.login(wxOpenIdToken);

        List<Module> menus = moduleService.findMenus(byUser);
        session.setAttribute("modules", menus);
        session.setAttribute("loginUser", byUser);
        return "home/main";
    }

    @RequestMapping("/weixinLoginqq")
    public String weixinLoginqq() {
        return "login/login-weixin";
    }

    public void showlist(){
        List<Feedback> list=null;
        Feedback feedback = new Feedback();
        feedback.setCompany_id(company_id);
        feedback.setStat(0);//未读
        User user = (User)session.getAttribute("loginUser");
        if (user.getDegree()==0){//sass
            feedback.setRadio("1");//sass可看
            list= feedbackService.showSass(feedback);
        }else{
            feedback.setRadio("2");//企业
            list= feedbackService.showlist(feedback);
        }
        session.setAttribute("data",list);
    }

}
